package com.ncc.interview.cache2;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author pengxiong
 * @date 2022/3/29
 * @Description 最近使用的缓存类
 * @since
 */
public class LatestCache<K, V> {

	private final Map<K, V> cacheMap = new ConcurrentHashMap<>();

	private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
	private Lock rlock = rwl.readLock();
	private Lock wlock = rwl.writeLock();

	public void put(K key, V value){
		wlock.lock();
		try{
			cacheMap.put(key, value);
		}finally {
			wlock.unlock();
		}
	}

	public V get(K key){
		rlock.lock();
		try{
			V value = cacheMap.get(key);
			if (value == null){
				System.out.println("缓存未命中，需要手动计算");
				value = calculate(key);
				cacheMap.put(key, value);
			}else{
				System.out.println("缓存命中");
			}
			return value;
		}finally {
			rlock.unlock();
		}
	}

	private V calculate(K key){
		Object o = new Object();
		return (V)o;
	}
}
